import uuid

from pubsub.brokers.redis import RedisBroker
from webutils.tornado.websocket import WebSocketHandler

from .. import broadcaster, tasks


class CheckInws(WebSocketHandler):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.broadcaster_app = None

    def check_origin(self, *args):
        return True

    async def open(self, unit_id=None, check_in_id=None):
        self.check_user_list = ''
        tag = uuid.uuid4().hex
        channel = f'ws:sign:{unit_id}:{check_in_id}'
        subkey = channel + ":sub"
        channels_subscribed = [channel, subkey]
        redis_pool_proxy = self.application.settings['DB_MAPPING']['api']
        redis_pool = redis_pool_proxy.raw

        broker = RedisBroker(
            redis_pool,
            tag,
            self.log_context,
        )
        self.broadcaster_app = broadcaster.CheckInBroadcaster(
            broker,
            tasks=tasks.tasks,
            channels_subscribed=channels_subscribed,
        )
        await self.broadcaster_app.start_consume(self)

        broker2 = RedisBroker(
            redis_pool,
            tag,
            self.log_context,
        )
        self.check_user_list = broadcaster.CheckInLlist(broker2, tasks={})
        await self.check_user_list.start_consume(channel)

        self.logger.info('check in websocket opened')

    async def on_message(self, data):
        self.logger.info(f'check in {data=}')

    def on_close(self) -> None:
        if self.check_user_list:
            self.check_user_list.while_status = False
